package com.nifostasky.comic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nifostasky.comic.common.threadlocal.SessionLoad;
import com.nifostasky.comic.entitys.SysOrg;
import com.nifostasky.comic.entitys.SysOrgUnitRel;
import com.nifostasky.comic.entitys.SysUnit;
import com.nifostasky.comic.exceptions.BusinessException;
import com.nifostasky.comic.mapper.SysUnitMapper;
import com.nifostasky.comic.service.SysOrgService;
import com.nifostasky.comic.service.SysOrgUnitRelService;
import com.nifostasky.comic.service.SysUnitService;
import com.nifostasky.comic.utils.PageUtils;
import com.nifostasky.comic.vos.ResultCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class SysUnitServiceImpl extends ServiceImpl<SysUnitMapper, SysUnit> implements SysUnitService {
    @Autowired
    private SysOrgUnitRelService sysOrgUnitRelService;
    @Autowired
    private SysOrgService sysOrgService;

    @Override
    public IPage<SysUnit> findListPage(PageUtils pageUtils, SysUnit sysUnit) {
        IPage<SysUnit> page = this.baseMapper.selectPage(new Page<>(pageUtils.getPageIndex(), pageUtils.getPageSize())
                , this.handleParams(sysUnit));
        if (Objects.nonNull(page) && CollectionUtils.isNotEmpty(page.getRecords())) {
            for (SysUnit unit : page.getRecords()) {
                this.handleBusInfo(unit);
            }
        }
        return page;
    }

    /**
     * 处理相关业务显示信息
     */
    private void handleBusInfo(SysUnit unit) {
        if (Objects.nonNull(unit.getOrgId())) {
            SysOrg org = sysOrgService.getById(unit.getOrgId());
            if (Objects.nonNull(org)) {
                unit.setOrgName(org.getOrgName());
            }
        }
        if (Objects.nonNull(unit.getParentId())) {
            SysUnit parentUnit = this.getById(unit.getParentId());
            if (Objects.nonNull(parentUnit)) {
                unit.setParentName(parentUnit.getUnitName());
            }
        }
    }

    @Override
    public List<SysUnit> findList(SysUnit sysUnit) {
        return this.list(this.handleParams(sysUnit));
    }

    /**
     * 组装查询参数
     *
     * @param sysUnit
     * @return
     */
    private LambdaQueryWrapper<SysUnit> handleParams(SysUnit sysUnit) {
        LambdaQueryWrapper<SysUnit> queryWrapper = new LambdaQueryWrapper<>();
        if (!SessionLoad.getLocalData().getSuperAdmin() && StringUtils.isBlank(sysUnit.getUnitCode())) {
            sysUnit.setUnitCode(SessionLoad.getLocalData().getUnitCode());
        }
        queryWrapper.like(StringUtils.isNotBlank(sysUnit.getUnitName()), SysUnit::getUnitName, sysUnit.getUnitName());
        queryWrapper.like(StringUtils.isNotBlank(sysUnit.getAliasName()), SysUnit::getAliasName, sysUnit.getAliasName());
        queryWrapper.like(StringUtils.isNotBlank(sysUnit.getPersonName()), SysUnit::getPersonName, sysUnit.getPersonName());
        queryWrapper.likeRight(StringUtils.isNotBlank(sysUnit.getOrgCode()), SysUnit::getOrgCode, sysUnit.getOrgCode());
        queryWrapper.likeRight(StringUtils.isNotBlank(sysUnit.getUnitCode()), SysUnit::getUnitCode, sysUnit.getUnitCode());
        queryWrapper.eq(Objects.nonNull(sysUnit.getOrgId()), SysUnit::getOrgId, sysUnit.getOrgId());
        queryWrapper.eq(Objects.nonNull(sysUnit.getParentId()), SysUnit::getParentId, sysUnit.getParentId());
        queryWrapper.eq(Objects.nonNull(sysUnit.getUnitType()), SysUnit::getUnitType, sysUnit.getUnitType());
        queryWrapper.eq(Objects.nonNull(sysUnit.getOrgLevel()), SysUnit::getOrgLevel, sysUnit.getOrgLevel());
        queryWrapper.eq(Objects.nonNull(sysUnit.getUnitStatus()), SysUnit::getUnitStatus, sysUnit.getUnitStatus());
        queryWrapper.eq(StringUtils.isNotBlank(sysUnit.getPersonPhone()), SysUnit::getPersonPhone, sysUnit.getPersonPhone());
        queryWrapper.orderByAsc(SysUnit::getSort).orderByDesc(SysUnit::getCreateDate);
        return queryWrapper;
    }

    @Override
    public Boolean deleteByIds(String ids) {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException(ResultCode.REQUIRED_PARAMS);
        }
        List<String> listId = Arrays.asList(ids.split(","));
        return this.removeByIds(listId);
    }

    @Override
    public Boolean saveOrUpdateUnit(SysUnit sysUnit) {
        //根据当前单位id删除所属区域与单位关联信息
       /* if(Objects.nonNull(sysUnit.getId())){
            sysOrgUnitRelService.deleteByUnitId(sysUnit.getId());
        }*/
        //填充org信息
        Boolean isAdd = false;
        if (Objects.isNull(sysUnit.getId())) {
            isAdd = true;
            SysOrg org = sysOrgService.getById(sysUnit.getOrgId());
            if (Objects.nonNull(org)) {
                sysUnit.setOrgCode(org.getOrgCode());
                sysUnit.setOrgLevel(org.getOrgLevel());
            }

        }

        Boolean bool = this.saveOrUpdate(sysUnit);
        /*if(CollectionUtils.isNotEmpty(sysUnit.getListSysOrgUnit())){
            sysUnit.getListSysOrgUnit().forEach(ou->{
                ou.setUnitId(sysUnit.getId());
            });
            sysOrgUnitRelService.saveBatch(sysUnit.getListSysOrgUnit());
        }*/
        if (isAdd) {
            //处理单位code
            StringBuffer sb = new StringBuffer();
            ;
            if (sysUnit.getParentId() == 0) {
                sysUnit.setParentId(sysUnit.getOrgId());
                sb.append(".").append(sysUnit.getParentId()).append(".").append(sysUnit.getId()).append(".");
                sysUnit.setUnitCode(sb.toString());
            } else {
                SysUnit parentUnit = this.getById(sysUnit.getParentId());
                sb.append(parentUnit.getUnitCode()).append(sysUnit.getId()).append(".");
            }
            //修改单位code
            this.updateUnitCodeById(sysUnit.getId(), sb.toString());
        }
        return bool;
    }

    @Override
    public SysUnit getDataById(Long id) {
        SysUnit sysUnit = this.getById(id);
        if (Objects.nonNull(sysUnit)) {
            List<SysOrgUnitRel> listOrgUnitRel = sysOrgUnitRelService.findListByUnitId(id);
            if (CollectionUtils.isNotEmpty(listOrgUnitRel)) {
                sysUnit.setListSysOrgUnit(listOrgUnitRel);
            }
        }
        return sysUnit;
    }

    @Override
    public Boolean updateUnitCodeById(Long id, String unitCode) {
        UpdateWrapper<SysUnit> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(SysUnit::getUnitCode, unitCode);
        updateWrapper.lambda().eq(SysUnit::getId, id);
        return this.update(updateWrapper);
    }
}
